package com.jdpc.weparty.component

import org.apache.commons.net.util.Base64
import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder
import java.security.Key
import java.security.KeyFactory
import java.security.KeyPairGenerator
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import java.util.HashMap
import javax.crypto.Cipher

object RSAUtil {
    const val privateKey = ("MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAM3uT+nLsVGC2fSo" +
    "IRGCpBDz0UiQ64FGeykzloaS8aJ8lpvP4RcOPkgcSVG/zCnM7WRIy0GZqTDKPpd1" +
    "uSwBr/HxjqKr4Njk/HGSAfUUTcEirJ8YEj0YYICNbOusCPtQozQCv18xC/rAYysj" +
    "rRiZsH0APrEH61xf9IrzHpM8V6/FAgMBAAECgYAQE1ZxrdD9x/UzwBw0vboJCL+B" +
    "pq57vQDISpqpjrcGNCudpjCwGBCMmIiwtQQ/DxxJA9W6HUCz6lXQhQQbh1YwrOQ1" +
    "g+NW1+Qptwnu/+opRcIsKd3jcU//A7+7pyU8ZEOeVc1Tw8nX4tvrKxmWIdFf3jeb" +
    "CNCHI0RzpNzkW8JbgQJBAPx+15JxQNM9iRT1iAYGpso4AWMMKG87at5ydx9VCO0z" +
    "hREY2aW8GBUcSi7D/e01EhVp/4ZldSLB4tmXILNdxxkCQQDQygS9UjwJMFECkgdI" +
    "qlIxc+tdpyQc3QMU66xzCdZKncoYGO7FRuUJKPQ4hpDLuy7kDUZmuViJrZtskTGm" +
    "3R+NAkEAzUTVPkGCIPly2y4tEjEQIW/ceMhmit80J3nJLBi2dBghQt//+QPsVCU2" +
    "jcRaSCCP/ga5bGpJCyOyp5B8TjWb6QJAVepLePxV6BIRw9UDWkt79w2UVL1qhtYL" +
    "Zph0JgJuQ9YaS0A3QMajiNlpZbk57Bvid8VeqvaqED14L3yvydJEIQJAJ8j24NOC" +
    "EEnaxDZd07DOuF43wI1Z1OlYp4vFibsCL1U5gi6P82+elomwkekx8U4AsObk7GUA" +
    "vNzjOEDMr4HGhA==")

    /**
     * RSA公钥加密
     *
     * @param str
     * 加密字符串
     * @param publicKey
     * 公钥
     * @return 密文
     * @throws Exception
     * 加密过程中的异常信息
     */
    @Throws(Exception::class)
    fun encrypt(str: String, publicKey: String?): String { //base64编码的公钥
        val decoded: ByteArray = Base64.decodeBase64(publicKey)
        val pubKey = KeyFactory.getInstance("RSA").generatePublic(X509EncodedKeySpec(decoded)) as RSAPublicKey
        //RSA加密
        val cipher = Cipher.getInstance("RSA")
        cipher.init(Cipher.ENCRYPT_MODE, pubKey)
        return Base64.encodeBase64String(cipher.doFinal(str.toByteArray(charset("UTF-8"))))
    }

    /**
     * RSA私钥解密
     *
     * @param str
     * 加密字符串
     * @param privateKey
     * 私钥
     * @return 铭文
     * @throws Exception
     * 解密过程中的异常信息
     */
    @Throws(Exception::class)
    fun decrypt(str: String, privateKey: String?): String { //64位解码加密后的字符串
        val inputByte: ByteArray = Base64.decodeBase64(str.toByteArray(charset("UTF-8")))
        //base64编码的私钥
        val decoded: ByteArray = Base64.decodeBase64(privateKey)
        val priKey = KeyFactory.getInstance("RSA").generatePrivate(PKCS8EncodedKeySpec(decoded)) as RSAPrivateKey
        //RSA解密
        val cipher = Cipher.getInstance("RSA")
        cipher.init(Cipher.DECRYPT_MODE, priKey)
        return String(cipher.doFinal(inputByte))
    }

    const val KEY_ALGORITHM = "RSA"
    //public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    private const val PUBLIC_KEY = "RSAPublicKey"
    private const val PRIVATE_KEY = "RSAPrivateKey"

    //获得公钥
    @Throws(Exception::class)
    fun getPublicKey(keyMap: Map<String, Any>): String { //获得map中的公钥对象 转为key对象
        val key = keyMap[PUBLIC_KEY] as Key?
        //byte[] publicKey = key.getEncoded();
    //编码返回字符串
        return encryptBASE64(key!!.encoded)
    }

    //获得私钥
    @Throws(Exception::class)
    fun getPrivateKey(keyMap: Map<String, Any>): String { //获得map中的私钥对象 转为key对象
        val key = keyMap[PRIVATE_KEY] as Key?
        //byte[] privateKey = key.getEncoded();
    //编码返回字符串
        return encryptBASE64(key!!.encoded)
    }

    //解码返回byte
    @Throws(Exception::class)
    fun decryptBASE64(key: String?): ByteArray {
        return BASE64Decoder().decodeBuffer(key)
    }

    //编码返回字符串
    @Throws(Exception::class)
    fun encryptBASE64(key: ByteArray?): String {
        return BASE64Encoder().encodeBuffer(key)
    }

    //map对象中存放公私钥
    @Throws(Exception::class)
    fun initKey(): Map<String, Any> { //获得对象 KeyPairGenerator 参数 RSA 1024个字节
        val keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM)
        keyPairGen.initialize(1024)
        //通过对象 KeyPairGenerator 获取对象KeyPair
        val keyPair = keyPairGen.generateKeyPair()
        //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
        val publicKey = keyPair.public as RSAPublicKey
        val privateKey = keyPair.private as RSAPrivateKey
        //公私钥对象存入map中
        val keyMap: MutableMap<String, Any> = HashMap(2)
        keyMap[PUBLIC_KEY] = publicKey
        keyMap[PRIVATE_KEY] = privateKey
        return keyMap
    }
}